﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint;
using TVMCORP.TVS.UTIL.Utilities;
using TVMCORP.TVS.UTIL;
using System.Data;

namespace TVMCORP.TVS.ControlTemplates.TVMCORP.TVS
{
    public partial class AdvancePaymentNewForm : UserControl
    {
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            //
            SPRibbon ribbon = SPRibbon.GetCurrent(this.Page);
            if (ribbon != null)
            {
                ribbon.TrimById("Ribbon.ListForm.Edit.Commit");
            }
            //
            repeaterRequestDetail.ItemDataBound += new RepeaterItemEventHandler(repeaterRequestDetail_ItemDataBound);
            linkButtonAdd.Click += new EventHandler(AddRequestDetail);
            btnSave.Click += new EventHandler(btnSave_Click);
            //
            GetUserInfo();
        }

        void btnSave_Click(object sender, EventArgs e)
        {
            if (!this.Page.IsValid)
                return;

            AddRequest();

            this.Page.Response.Clear();
            this.Page.Response.Write(
            string.Format(System.Globalization.CultureInfo.InvariantCulture, @"<script type='text/javascript'> window.frameElement.commonModalDialogClose(1, '{0}');</script>", ""));
            this.Page.Response.End();
        }

        void AddRequestDetail(object sender, EventArgs e)
        {
            DataTable dataTable = MakeRequestDetail();
            repeaterRequestDetail.DataSource = dataTable;
            repeaterRequestDetail.DataBind();
        }

        void repeaterRequestDetail_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            DataRowView rowView = (DataRowView)e.Item.DataItem;
            if (rowView != null)
            {
                Literal literalOrderValue = e.Item.FindControl("literalOrder") as Literal;
                literalOrderValue.Text = (e.Item.ItemIndex + 1).ToString();

                TextBox txtContent = e.Item.FindControl("txtContent") as TextBox;
                txtContent.Text = rowView["Content"].ToString();

                TextBox txtAmount = e.Item.FindControl("txtAmount") as TextBox;
                txtAmount.Text = rowView["Amount"].ToString();
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //Load purchase detail
                DataTable RequestDetail = MakeRequestDetail();
                repeaterRequestDetail.DataSource = RequestDetail;
                repeaterRequestDetail.DataBind();
            }
        }

        #region Private Functions

        private string GetUserInfo()
        {
            string output = string.Empty;
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite site = new SPSite(SPContext.Current.Site.ID))
                    {
                        using (SPWeb web = site.OpenWeb())
                        {
                            SPListItemCollection userItems = web.Lists.TryGetList(web.SiteUserInfoList.Title).GetItems();

                            SPListItem userItem = web.Lists.TryGetList(web.SiteUserInfoList.Title).GetItemById(SPContext.Current.Web.CurrentUser.ID);
                            if (userItem != null)
                            {
                                literalDateRequestValue.Text = DateTime.Now.ToString("dd/MM/yyyy");
                                literalUserRequestValue.Text = userItem["Title"].ToString();
                                literalDepartmentRequestValue.Text = userItem["Department"] == null ? string.Empty : userItem["Department"].ToString();
                            }
                        }
                    }
                });
            }
            catch (Exception ex)
            {
                output = ex.Message;
            }

            return output;
        }

        private DataTable MakeRequestDetail()
        {
            DataTable dataTable = null;
            if (ViewState["PaymentDetail"] == null)
            {
                dataTable = new DataTable();
                DataColumn[] dataColumn = new DataColumn[]{
                    new DataColumn("Content"),
                    new DataColumn("Amount")
                };
                dataTable.Columns.AddRange(dataColumn);
            }
            else
            {
                dataTable = ViewState["PaymentDetail"] as DataTable;
                dataTable.Clear();

                foreach (RepeaterItem RequestDetail in repeaterRequestDetail.Items)
                {
                    TextBox txtContent = RequestDetail.FindControl("txtContent") as TextBox;
                    TextBox txtAmount = RequestDetail.FindControl("txtAmount") as TextBox;

                    if (!string.IsNullOrEmpty(txtContent.Text))
                    {
                        DataRow row = dataTable.NewRow();
                        row[0] = txtContent.Text;
                        row[1] = txtAmount.Text;
                        dataTable.Rows.Add(row);
                    }
                }
            }

            DataRow emptyRow = dataTable.NewRow();
            emptyRow[0] = string.Empty;
            emptyRow[1] = string.Empty;
            dataTable.Rows.Add(emptyRow);
            ViewState["PaymentDetail"] = dataTable;

            return dataTable;
        }

        private void AddRequest()
        {
            SPFieldLookupValueCollection requestDetails = new SPFieldLookupValueCollection();

            var RequestDetailList = Utility.GetListFromURL(Constants.REQUEST_DETAIL_LIST_URL, SPContext.Current.Web);
            foreach (RepeaterItem RequestDetail in repeaterRequestDetail.Items)
            {
                TextBox txtContent = RequestDetail.FindControl("txtContent") as TextBox;
                TextBox txtAmount = RequestDetail.FindControl("txtAmount") as TextBox;
                if (!string.IsNullOrEmpty(txtContent.Text))
                {
                    SPListItem requestDetailItem = RequestDetailList.AddItem();
                    requestDetailItem["Title"] = txtContent.Text;
                    requestDetailItem["Amount"] = txtAmount.Text.Replace(",", string.Empty);
                    requestDetailItem.Update();
                    SPFieldLookupValue spFieldLookupValue = new SPFieldLookupValue(requestDetailItem.ID, requestDetailItem.Title);
                    requestDetails.Add(spFieldLookupValue);
                }
            }

            SPListItem currentItem = SPContext.Current.ListItem;
            currentItem[SPBuiltInFieldId.Title] = ffTitle.Value;
            currentItem["DateRequest"] = DateTime.Now;
            currentItem["UserRequest"] = SPContext.Current.Web.CurrentUser;
            currentItem["DepartmentRequest"] = literalDepartmentRequestValue.Text;
            currentItem["RequestDetail"] = requestDetails;
            currentItem["References"] = ffReferences.Value;
            currentItem["Currency"] = rdbVND.Text;
            if (rdbUSD.Checked)
                currentItem["Currency"] = rdbUSD.Text;
            if (peChief.IsValid && peChief.ResolvedEntities.Count > 0)
                currentItem["Chief"] = SPContext.Current.Web.EnsureUser(((PickerEntity)peChief.ResolvedEntities[0]).Key);
            if (peAccountant.IsValid && peAccountant.ResolvedEntities.Count > 0)
                currentItem["Accountant"] = SPContext.Current.Web.EnsureUser(((PickerEntity)peAccountant.ResolvedEntities[0]).Key);
            if (peHeadAccountant.IsValid && peHeadAccountant.ResolvedEntities.Count > 0)
                currentItem["HeadAccountant"] = SPContext.Current.Web.EnsureUser(((PickerEntity)peHeadAccountant.ResolvedEntities[0]).Key);
            if (peApprover.IsValid && peApprover.ResolvedEntities.Count > 0)
                currentItem["Approver"] = SPContext.Current.Web.EnsureUser(((PickerEntity)peApprover.ResolvedEntities[0]).Key);

            SaveButton.SaveItem(SPContext.Current, false, "");
        }

        #endregion Private Functions
    }
}
